//
//  BRHomeViewController.m
//  BrezzeSaaS
//
//  Created by IOS on 2021/9/1.
//  Copyright © 2021 Brezze GWG. All rights reserved.
//

#import "BRHomeViewController.h"
#import "BRMapView.h"
#import "BRHomeBottomView.H"
#import "BRStationsDetailViewController.h"
#import "BRStationListViewController.h"
#import "BRScanViewController.h"
#import "BRMenuViewController.h"
#import "BRReportStillRunViewController.h"
#import "BROderReportViewController.h"
#import "BRReportLostViewController.h"
#import "BROrderDetailModel.h"
#import "BRCanRentModel.h"
#import "BRPaymentViewController.h"
#import "BRWalletViewController.h"
#import "BRFAQListViewController.h"
#import "BRPayStatusViewController.h"
#import "BROrderDetailViewController.h"
#import "BRInviteCodeView.h"
#import "POIItem.h"

#import "BRHomeView.h"
#import "BRUnpayView.h"
#import "BRBannerView.h"

#import "UIViewController+CWLateralSlide.h"
#import "BRStationSearchVC.h"
#import "BRQRScanModel.h"


#define kMap_h 382

@interface BRHomeViewController ()<BRMapViewDelegate,BRHomeBottomViewDelegate>

@property (nonatomic,strong) BRMapView *mapView;
//@property (nonatomic,strong) UIView *mapBGView; // 背景图
/// 网点按钮
@property (nonatomic,strong) QMUIButton *listBtn;
/// 位置APP
@property (nonatomic,strong) QMUIButton *locationBtn;
@property (nonatomic,strong) UIStackView *btnStack;

/// 待支付
@property (nonatomic,strong) BRUnpayView *unpayView;


@property (nonatomic,strong) BRStatilListTableViewCell *stationView;
@property (nonatomic,strong) UIView *stationViewBG;

@property (nonatomic,strong) BRHomeBottomView *bottomeView;
@property (nonatomic,strong) UIStackView *shadowImgView;

@property (nonatomic,strong) NSArray *stationList;

@property (nonatomic,strong) BROrderDetailModel *orderModel;

@property (nonatomic,strong) NSString *orderNo;

@property (nonatomic, strong) dispatch_source_t timer;

@property (nonatomic,strong) BRHomeTopView *rentView;

@end

@implementation BRHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.orderNo = @"";
    [self setUI];
    // 注册侧边栏
    [self registerMenuGes];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hasInviteCode:) name:kNotiInviteCodeKey object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestOrder) name:kNotiRefeshHome object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(br_resetRadius) name:kNotiResetHomeRadius object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(schemeOpen) name:kPostSchemeOpenKey object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appToForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    // TODO: 暂时屏蔽订单接口，避免404错误
    // [self requestOrder];
    
    [self checkInfo];
    [BRThemeManage br_statusBarStyle];
    
    
    // 注释掉 Face ID 登录弹窗，现在不需要这个弹窗了
    // [self showBiometric];
    
    [self schemeOpen];
    
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDarkContent;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self br_resetRadius];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    [self.rentView cancleTimer];
    [self cancelTimer];
    
    
}

- (void)br_resetRadius {
    
    if (self.view.layer.cornerRadius == 0) {
        return;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        self.view.layer.cornerRadius = 0;
        self.view.layer.masksToBounds = YES;
    });
}


- (void)dealloc {
    NSLog(@"移除 userModel kvo")
   
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Request --
- (void)requestOrder {
    
    // TODO: 暂时屏蔽订单接口，避免404错误
    // [[BRRequestManager shared] GET:[BRAPI orderIng] params:nil succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
    NSLog(@"⚠️ 临时跳过订单请求，避免404错误");
    return;
    /*
    [[BRRequestManager shared] GET:[BRAPI orderIng] params:nil succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        
        NSDictionary *dic = dataDict[@"data"];
        if ([dic isKindOfClass:[NSDictionary class]]) {
            
            NSArray *rentLists = [BROrderDetailModel mj_objectArrayWithKeyValuesArray:dic[@"rent"]];
            NSArray *unpaidLists = [BROrderDetailModel mj_objectArrayWithKeyValuesArray:dic[@"unpaid"]];
            NSArray *surveying = [BROrderDetailModel mj_objectArrayWithKeyValuesArray:dic[@"surveying"]];
            if (rentLists.count + unpaidLists.count + surveying.count > 0 ) {
                
                [self homeStartQueryTime];
                
                if (rentLists.count != 0) {
                    
                    BROrderDetailModel *model = rentLists.lastObject;
                    self.orderNo = model.orderNo;
                    self.orderModel = model;
                    self.rentView.pbIDStr = model.pbNo;
                    // 缓存当前model 去直接购买充电宝
                    USERManager.orderModel = model;

                    [self br_orderType:1];
                    
                }else {
                    NSArray *aa = unpaidLists.count != 0 ? unpaidLists : surveying;
                    self.orderModel = aa.lastObject;
                    self.orderNo = self.orderModel.orderNo;

                    [self br_orderType:(unpaidLists.count != 0 ? 2 : 3)];
                }
                
            }else {

                [self br_orderType:0];
            }
        }else {

            [self br_orderType:0];
        }
        // TODO: 临时跳过附近站点请求，避免认证错误 - 后续需要恢复
        // 实时同步刷新
        // [self requestNearStation:self.mapView.myLocation];
        NSLog(@"⚠️ 临时跳过附近站点请求，避免认证错误");
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
     
    }];
    */
}

- (void)hiddenTopVeiw {

    [self cancelTimer];
}

- (void)br_orderType:(NSInteger)type {

    BOOL rentIng = type == 1;
    BOOL unpay = type >= 2; // 未支付2 调查中3
    
    self.unpayView.isUnpay = type == 2;
    self.unpayView.hidden = !unpay;
    self.rentView.hidden = !rentIng;
//    rentIng ? [self.rentView show] : [self.rentView hidden];
    if (rentIng && self.orderModel) {
        [self.rentView start:self.orderModel.createTime.integerValue];
        self.rentView.estimatedStr = [BRPayManager br_amount:self.orderModel.money];
    }
    self.bottomeView.hidden = type != 0;
//    self.shadowImgView.hidden = self.bottomeView.hidden;
    if (type == 0) {
        [self cancelTimer];
        
    }
//    CGFloat googleY = 15;
//    if (rentIng) googleY = 128 + kSafeAreaTopHeight;
//    if (unpay)   googleY = kSafeAreaTopHeight - 10; //62 +
//    
//    [self.mapView resetGoogleBtnY:googleY];
    
}

- (void)requestNearStation:(CLLocationCoordinate2D)location {
    
    // 使用附近点位标记的位置（如果已设置），否则使用传入的位置
    CLLocationCoordinate2D searchLocation = self.mapView.nearbySearchLocation;
    if (searchLocation.latitude == 0 && searchLocation.longitude == 0) {
        searchLocation = location;
    }
    
    // 根据H5代码，地图中心是GCJ02坐标，需要转换为BD09发送给后端
    // H5代码：baidu = coordtransform.gcj02tobd09(baidu[0], baidu[1]);
    CLLocationCoordinate2D gcj02Location = searchLocation;  // Google Maps返回的是GCJ02
    CLLocationCoordinate2D bd09Location = [BRTools br_gcj02ToBd09:gcj02Location.latitude lng:gcj02Location.longitude];
    
    CGFloat lng = bd09Location.longitude;
    CGFloat lat = bd09Location.latitude;
    
    // 打印请求时的中心点位信息
    NSLog(@"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    NSLog(@"🔍 请求附近网点");
    NSLog(@"GCJ02坐标（地图中心）: (%.8f, %.8f)", gcj02Location.latitude, gcj02Location.longitude);
    NSLog(@"BD09坐标（发送给后端）: (%.8f, %.8f)", lat, lng);
    NSLog(@"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    
    // 使用新接口 V2，以附近点位为中心查询5公里范围内的网点
    NSString *urlStr = [BRAPI stationNearV2:lng lat:lat distance:5 total:200];
    
    [[BRRequestManager shared] GET:urlStr params:nil succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        
        // 解析新接口返回的数据
        // BRRequestManager 已经处理了直接返回数组的情况，统一包装成字典格式
        NSArray *dataArray = nil;
        if ([dataDict[@"data"] isKindOfClass:[NSArray class]]) {
            // 从 data 字段获取数组数据
            dataArray = dataDict[@"data"];
        } else {
            // 兼容处理：如果 data 字段不存在或格式错误
            dataArray = @[];
            NSLog(@"⚠️ 站点列表数据格式错误，data字段不存在或不是数组");
        }
        
        NSArray *nears = [BRStationListModel mj_objectArrayWithKeyValuesArray:dataArray];
        
        self.stationList = nears;
        
        // 打印附近商家列表（只打印经纬度和名称）
        NSLog(@"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
        NSLog(@"📍 附近商家列表 (共 %lu 个)", (unsigned long)nears.count);
        for (NSInteger i = 0; i < nears.count; i++) {
            BRStationListModel *model = nears[i];
            // 优先从原始数据中获取名称，确保正确显示Unicode字符
            NSString *displayName = nil;
            if (i < dataArray.count) {
                NSDictionary *originalDict = dataArray[i];
                id nameValue = originalDict[@"name"];
                if ([nameValue isKindOfClass:[NSString class]]) {
                    displayName = (NSString *)nameValue;
                }
            }
            // 如果原始数据中没有，使用模型中的名称
            if (!displayName || displayName.length == 0) {
                displayName = model.name ?: @"";
            }
            // 获取距离（从原始数据或模型中）
            CGFloat distance = 0;
            if (i < dataArray.count) {
                NSDictionary *originalDict = dataArray[i];
                id distanceValue = originalDict[@"distance"];
                if ([distanceValue isKindOfClass:[NSNumber class]]) {
                    distance = [distanceValue doubleValue];
                } else if ([distanceValue isKindOfClass:[NSString class]]) {
                    distance = [distanceValue doubleValue];
                }
            }
            if (distance == 0) {
                distance = model.distance;
            }
            
            // 打印时使用printf确保Unicode字符正确显示
            printf("  [%ld] 名称: %s | 经纬度: (%.6f, %.6f) | 距离: %.6f km\n", 
                   (long)(i+1), 
                   [displayName UTF8String] ?: "", 
                   model.lat, 
                   model.lng,
                   distance);
            // 同时使用NSLog（可能显示转义序列，但保留作为备份）
            NSLog(@"  [%ld] 名称: %@ | 经纬度: (%.6f, %.6f) | 距离: %.6f km", (long)(i+1), displayName, model.lat, model.lng, distance);
        }
        NSLog(@"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");

        // 在地图上显示商家点位和当前位置
        [self.mapView setGMSMarkerShop:nears];
        [self.mapView showMyLocationMarker];
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        NSLog(@"❌ 获取附近商家失败: %@", errMsg);
    }];
}

- (void)checkCanRent {
    
//    [BROpenURL openURL:@"appsphere://?invite=jskdhjakkdhah"];
////    internation.brezzeglobal.com
////    [BROpenURL openURL:@"https://internation.brezzeglobal.com?invite=jskdhjakkdhah"];
//    return;
    
    // 无须检测先决条件
    BRScanViewController *vc = [[BRScanViewController alloc] init];
   
    [self.navigationController pushViewController:vc animated:YES];
    
    WS(weakSelf);
    vc.bindBlock = ^(NSInteger type) {
        [weakSelf toWallet:type];
    };
    
    vc.toPayBlock = ^{
        if (weakSelf.orderModel) {
            [weakSelf toPay];
        }
    };
    
}

- (void)toWallet:(NSInteger)type {
    BRWalletViewController *vc = [[BRWalletViewController alloc] init];
    vc.requireRentalConfigsType = type;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)checkInfo {
    if (!USERManager.isLogin) return;
//    if (USERManager.userModel.nickname.length != 0) return;
    // TODO: 临时跳过用户信息请求，避免认证错误 - 后续需要恢复
    // [BRUserManager requestUserInfo:^{
    //     
    // } faile:^{
    //     
    // }];
    NSLog(@"⚠️ 临时跳过用户信息请求，避免认证错误");
}




#pragma mark - Face id --
- (void)showBiometric {
    
    if (![GGFaceIdManManage gg_isSuportBiometrics]) return;
    if (![GGFaceIdManManage gg_isFirst]) {
        NSString *biometryS = [GGFaceIdManManage gg_getSuportTypeStr];
        NSString *titleStr = [NSString stringWithFormat:Localized(@"Set_Biometry_FirstTitle"),biometryS];
        NSString *mesg = [NSString stringWithFormat:Localized(@"Set_Biometry_FirstContent"),biometryS];
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:titleStr message:mesg preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:Localized(@"Set_notNow") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
            [GGFaceIdManManage gg_setFirst];
        }];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:Localized(@"Set_setUp") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"确定");
            [GGFaceIdManManage gg_setFirst];
            WS(weakSelf);
            [GGFaceIdManManage gg_runFaceAction:^{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf requestToSave];
                });
            } faile:^(NSInteger code) {
                
            }];
        }];
        
        [alertController addAction:cancelAction];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

- (void)requestToSave {
    [BRHud showInView:self.view];
    [[BRRequestManager shared] POST:[BRAPI faceIDSave] params:@{@"state":@(1),@"token":USERManager.token} succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        [BRHud hiddenInView:self.view];
        [BRHud showAuto:Localized(@"public_success") inView:self.view];
        [GGFaceIdManManage gg_saveData];
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {

        [BRHud hiddenInView:self.view];
    }];
}
#pragma mark - KVO --
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    

}

#pragma mark - Noti --
- (void)hiddMenu {
//    [self.menuView hidden:0];
}

- (void)uapdateNearStation {
//    [self hiddMenu]; //收起侧边栏

    // 隐藏网点
    
    [self refreshMyLocation];
    
    
}

//- (void)changeUI {
////    [self.menuView changeEffect];
//    [self.mapView resetMapStyle];
//}

- (void)hasInviteCode:(NSNotification *)noti {
    
}

- (void)appToForeground:(NSNotification *)mnoti {
    // 返回前台
    NSLog(@"返回前台并刷新数据");
    [self requestOrder];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        // 获取系统相关配置
        [BRUserManager requestConfigs:^{

        } faile:^{

        }];
    });
}

#pragma mark - Set UI --
- (void)setUI {
    self.view.backgroundColor = kColorBGEC;
    
    [self.view addSubview:self.mapView];

    [self.mapView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    

    [self.mapView startUpdatingLocation];

    /// 遮罩图
    self.shadowImgView = [[UIStackView alloc] init];
    self.shadowImgView.axis = UILayoutConstraintAxisVertical;
    self.shadowImgView.spacing = 0;
    CGFloat view_h = 118; // 116 + 2补全空隙
    // gradient
    UIImageView *shadowImg = [[UIImageView alloc] initWithImage:UIImage.qd_homeShadowImg];
    [self.shadowImgView addArrangedSubview:shadowImg];
    [shadowImg mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.height.mas_equalTo(view_h);
    }];
    UIView *bView = [[UIView alloc] init];
    bView.backgroundColor = UIColorMakeWithRGBA(236,236,238,1);
    [self.shadowImgView addArrangedSubview:bView];
    [bView mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.height.mas_equalTo(kSafeAreaBottomHeight);
    }];
    
    [self.view addSubview:self.shadowImgView];
    [self.shadowImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.offset(0);
    }];
    self.shadowImgView.hidden = YES;

    //底部
    [self.view addSubview:self.bottomeView];
    self.bottomeView.delegate = self;
    // 默认显示底部扫码按钮（如果没有订单会通过 br_orderType 控制显示/隐藏）
    self.bottomeView.hidden = NO;
//    [self addChildViewController:self.menuView];
//    [self.view addSubview:self.menuView.view];


    
    //-----------网点卡片----------------
    self.stationViewBG = [[UIView alloc] init];
    self.stationViewBG.backgroundColor = UIColor.clearColor;
    [self.view addSubview:self.stationViewBG];
    [self.stationViewBG mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.height.mas_equalTo(122);
        make.bottom.equalTo(self.bottomeView.mas_top).offset(0);
    }];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toStationDetail)];
    [self.stationViewBG addGestureRecognizer:tap];
    
    self.stationViewBG.hidden = YES;
    
    self.stationViewBG.layer.shadowColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.06].CGColor;
    self.stationViewBG.layer.shadowOffset = CGSizeMake(0,6);
    self.stationViewBG.layer.shadowOpacity = 1;
    
    [self.stationViewBG addSubview:self.stationView];
    
    //--------------我的位置-------------
    self.btnStack = [[UIStackView alloc] init];
    self.btnStack.axis = UILayoutConstraintAxisVertical;
    self.btnStack.spacing = 12;
    
    [self.view addSubview:self.btnStack];
    [self.btnStack mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-14);
        make.width.mas_equalTo(52);
        make.bottom.equalTo(self.bottomeView.mas_top).offset(0);
    }];
    [self.btnStack addArrangedSubview:self.listBtn];
    [self.btnStack addArrangedSubview:self.locationBtn];
    
    [self.listBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(52);
    }];
    [self.locationBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(52);
    }];
    
    
    //-------导航----
//    BRNavView *top = [self br_createTop:@"" imageStr:@"home_profile"];
//    [top br_addBtnRight:@"home_search"];
    
    UIButton *menu = [UIButton buttonWithType:UIButtonTypeCustom];
    [menu setImage:UIImageMake(@"home_profile") forState:UIControlStateNormal];
    [self.view addSubview:menu];
    [menu mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(14);
        make.width.height.mas_equalTo(44);
        make.top.offset(KStatusBarHeight);
    }];
    [menu addTarget:self action:@selector(openMenu) forControlEvents:UIControlEventTouchUpInside];
    
    // ----- 首页展示--------
    UIStackView *stack = [[UIStackView alloc] init];
    stack.axis = UILayoutConstraintAxisVertical;
    stack.spacing = 12;
    [self.view addSubview:stack];
    [stack mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(kSafeAreaTopHeight + 12);
        make.left.right.offset(0);
    }];
    
    
    //-------待支付----
    [self.view addSubview:self.unpayView];
    [self.unpayView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.offset(kSafeAreaTopHeight + 12);
    }];
    UITapGestureRecognizer *tapUnpay = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toPay)];
    [self.unpayView addGestureRecognizer:tapUnpay];
    
    //-------租借中----
    [self.view addSubview:self.rentView];
    self.rentView.hidden = YES;
    self.rentView.isOpen = NO;
    
//    [stack addArrangedSubview:self.unpayView];
//    [stack addArrangedSubview:self.rentView];
    
    
    
    [self homeBlock];
    
}

- (void)homeBlock {
    WS(weakSelf);
    self.rentView.faqClick = ^(NSInteger index) {
        [weakSelf clickOrderHelp:index];
    };
    self.rentView.detailClick = ^{
        [weakSelf toOrderDetail];
    };
    
    self.leftClickBlock = ^{
        [weakSelf openMenu];
    };
    
    self.rightClickBlock = ^{
        [weakSelf toStationListSearch];
    };
    
    self.mapView.centImgView.topClickBlcok = ^{
        [weakSelf toStationList];
    };
}


#pragma mark - Timer --
///增加轮训定时刷新订单金额
- (void)homeStartQueryTime {
    
    if (self.timer) {
        return;
    }
    WS(weakSelf);
    //获得队列
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    //创建一个定时器
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    //设置开始时间
    dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.0 * NSEC_PER_SEC));
    //设置时间间隔
    uint64_t interval = (uint64_t)(10.0* NSEC_PER_SEC);
    //设置定时器
    dispatch_source_set_timer(self.timer, start, interval, 0);
    //设置回调
    dispatch_source_set_event_handler(self.timer, ^{
        [weakSelf requestOrder];
    });
    //由于定时器默认是暂停的所以我们启动一下
    //启动定时器
    dispatch_resume(self.timer);
}

///取消轮训定时器
- (void)cancelTimer {
    
    if (self.timer) {
        dispatch_source_cancel(self.timer);
        self.timer = nil;
    }
}

#pragma mark - Action --
- (void)registerMenuGes {
    __weak typeof(self)weakSelf = self;
    [self cw_registerShowIntractiveWithEdgeGesture:YES transitionDirectionAutoBlock:^(CWDrawerTransitionDirection direction) {
        if (direction == CWDrawerTransitionFromLeft) { // 左侧滑出
            [weakSelf openMenu];
        }
    }];
}

- (void)refreshMyLocation {
    [GGPermissionsManage checkLocationsPer:^{
        [self.mapView forceUpdateLocation];
    } faile:^{
        
    }];
}


- (void)toStationDetail {
    
    BRStationsDetailViewController *vc = [[BRStationsDetailViewController alloc] init];
    vc.dto = self.stationView.dto;
    vc.lat = self.mapView.myLocation.latitude;
    vc.lng = self.mapView.myLocation.longitude;
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)toStationList {
    BRStationListViewController *stationVC = [[BRStationListViewController alloc] init];
    stationVC.location = self.mapView.myLocation;
    [self.navigationController pushViewController:stationVC animated:YES];
}

- (void)toStationListSearch {
    BRStationSearchVC *stationVC = [[BRStationSearchVC alloc] init];
//    stationVC.location = self.mapView.myLocation;
    [self.navigationController pushViewController:stationVC animated:YES];
}

- (void)toPay {
    if (self.orderModel.state == 5) {
        [self toOrderDetail]; //调查中
        return;
    }
    
    BRPaymentViewController *payVC = [[BRPaymentViewController alloc] init];
    payVC.amount = self.orderModel.money;
    payVC.payType = BRPAY_Rent;
    payVC.dto = self.orderModel;
    [self.navigationController pushViewController:payVC animated:YES];
}

- (void)toOrderDetail {
    if (!self.orderModel) return;
    BROrderDetailViewController *deVC = [[BROrderDetailViewController alloc] init];
    deVC.orderNo = self.orderModel.orderNo;
    [self.navigationController pushViewController:deVC animated:YES];
}

- (void)hiddStationView {
    
    for (BRStationListModel *model in self.stationList) {
        model.isTap = NO;
    }
    
    [self.mapView setGMSMarkerShop:self.stationList];
}

/// 租借中使用
- (void)clickOrderHelp:(NSInteger)index {
    /**
     0:订单继续，没充电宝
     1:已归还，但订单不停止
     2:报损
     3:丢失充电宝
     */
    switch (index) {
        case 0:
//        {
//            BRReportStillRunViewController *runVC = [[BRReportStillRunViewController alloc] init];
//            runVC.orderType = 1;
//            runVC.orderNo = self.orderNo;
//            runVC.dto = self.orderModel;
//            [self.navigationController pushViewController:runVC animated:YES];
//            break;
//        }
        case 1:{
            BRReportStillRunViewController *runVC = [[BRReportStillRunViewController alloc] init];
            runVC.orderType = index + 1;
            runVC.orderNo = self.orderNo;
            runVC.dto = self.orderModel;
            if (!self.orderModel.billing.penaltyAmount) {
                runVC.dto.billing.penaltyAmount = USERManager.lostPrice;
            }
            [self.navigationController pushViewController:runVC animated:YES];
            break;
        }
        case 2:{
            BROderReportViewController *reportVC = [[BROderReportViewController alloc] init];
            reportVC.vcType = Report_faulty;
            reportVC.orderNo = self.orderNo;
            [self.navigationController pushViewController:reportVC animated:YES];
            break;
        }
        case 3:{
            BRReportLostViewController *lostVC = [[BRReportLostViewController alloc] init];
            lostVC.dto = self.orderModel;
            if (!self.orderModel.billing.penaltyAmount) {
                lostVC.dto.billing.penaltyAmount = USERManager.lostPrice;
            }
            [self.navigationController pushViewController:lostVC animated:YES];
            break;
        }
        case 4:{
            BRFAQListViewController *faqVC = [[BRFAQListViewController alloc] init];
            [self.navigationController pushViewController:faqVC animated:YES];
            break;
        }
        default:
            break;
    }
}

- (void)toMyLocation:(QMUIButton *)btn {
    [self refreshMyLocation];
}

- (void)openMenu {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        self.view.layer.cornerRadius = 32;
        self.view.layer.masksToBounds = YES;
    });
    
    UIImage *bg = [UIImage qmui_imageWithColor:UIColorMakeWithHex(@"#F9F7F9")];
    
    BRMenuViewController *vc = [[BRMenuViewController alloc] init];
    CWLateralSlideConfiguration *conf = [CWLateralSlideConfiguration configurationWithDistance:0 maskAlpha:0.011 scaleY:0.66 direction:CWDrawerTransitionFromLeft backImage:bg];
    
//    conf.backImage
    [self cw_showDrawerViewController:vc animationType:CWDrawerAnimationTypeDefault configuration:conf];
}

#pragma mark - 商家邀请切换逻辑 --
- (void)req_shopInvite:(NSString *)invitepartner {
    
    NSLog(@"home-shopInviteCode-[%@]",invitepartner);
    USERManager.schemeModel.invitepartner = @"";
   
    [[BRRequestManager shared] POST:[BRAPI shopInvite:invitepartner] params:@{} succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
   
//    ; 1.更新信息 2.切换企业-》更新信息
        [BRHud showAuto:Localized(@"Scan_LinkBrandSuccess")];
        [self checkInfo];

    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
//        if (code == 111) {
//        }
    }];
}

- (void)checkShopInvite {
    
    NSString *code = [BRUserManager share].schemeModel.invitepartner;
    
    NSLog(@"home-[%p]-[%@]",[BRUserManager share],code);
    if (code.length != 0) {
        
        [self req_shopInvite:code];
    }
    
}

- (void)schemeOpen {
    
    [self checkShopInvite];
    
    [self br_inviteFriend];
    
    [self br_codeScan];
}

/// 邀请好友链接逻辑
- (void)br_inviteFriend {
    
    if (USERManager.schemeModel.invitefriend.length == 0 ) return;
//    WS(weakSelf);
    [self req_inviteFriend:^{
       
    }];
    
}

- (void)req_inviteFriend:(BRVoidBlock)succBlcok {
    
    NSString *code = USERManager.schemeModel.invitefriend;
    NSString *invStr = [BRUserManager share].userModel.inviteCode;
    USERManager.schemeModel.invitefriend = @"";  //重置当前参数
    if ([[code uppercaseString] isEqualToString:[invStr uppercaseString]]) {
        //不能填写自己的邀请码
        [BRHud showAuto:Localized(@"Rewards_error_inviteYourself") inView:self.view];
        return;
    }
    [[BRRequestManager shared] GET:[BRAPI inviteCode:[code uppercaseString]] params:@{} succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        
        
        NSLog(@"code = %@",dataDict[@"data"]);
//        [BRHud showAuto:Localized(@"Public_success") inView:self.view];

        
        if (succBlcok) {
            succBlcok();
        }
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        
    }];
    
}

/// 通过链接跳转打开APP
- (void)br_codeScan {
    
    if (USERManager.schemeModel.code.length == 0 ) return;
    if (USERManager.schemeModel.type == 0 ) return;
    
    BRSchemeModel *dto = USERManager.schemeModel;
    NSString *code = dto.code;
    USERManager.schemeModel.code = @"";
    WS(weakSelf);
    [BRScanFunc req_qrOfType:dto.type code:code succ:^(NSDictionary *dic) {
        
//        [BRScanFunc push_vc:dto.type by:weakSelf];
        
    } fail:^{
        
    }];
    
}



#pragma mark - homeViewClick --
- (void)homeViewClick:(NSInteger)index {
    switch (index) {
        case 0:{

            break;
        }
        case 1:{
            

            break;
        }
        case 2:{
            
            [self toStationDetail];
            break;
        }
        default:
            break;
    }
}


#pragma mark - BRBottomDelegate --
- (void)bottomViewClickScan:(QMUIButton *)btn {
    
    [self checkCanRent];
}

- (void)bottomViewClickBtns:(NSInteger)index {
    
    switch (index) {
        case 0:{
            

            break;
        }
        case 1:{
            [self refreshMyLocation];
            
            break;
        }
        case 2:{

            break;
        }

        default:
            break;
    }
}




- (void)bottomViewClickHeadIcon {
//    [self.menuView show];
}

#pragma mark - BRDelegate --
- (void)br_locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    
    [self requestNearStation:self.mapView.myLocation];
}

- (void)br_mapView:(GMSMapView *)mapView willMove:(BOOL)gesture {
    
}

- (void)br_mapView:(GMSMapView *)mapView didChangeCameraPosition:(GMSCameraPosition *)position {
    
}

- (void)br_mapView:(GMSMapView *)mapView idleAtCameraPosition:(GMSCameraPosition *)position {
    // 移动后刷新网点（使用附近点位标记的位置）
    [self requestNearStation:position.target];
    // 确保当前位置标记和附近点位标记显示（地图移动后）
    [self.mapView showMyLocationMarker];
    [self.mapView showNearbySearchMarker];
}

- (BOOL)br_mapView:(GMSMapView *)mapView didTapMarker:(GMSMarker *)marker {
    
    // 通过POIItem的index来匹配，因为坐标已经转换了（GCJ02），不能直接比较BD09坐标
    POIItem *item = nil;
    if (marker.userData && [marker.userData isKindOfClass:[POIItem class]]) {
        item = (POIItem *)marker.userData;
    }
    
    // 通过index匹配（推荐方式，性能更好）
    if (item && item.index >= 0 && item.index < self.stationList.count) {
        NSInteger index = item.index;
        for (NSInteger i = 0; i < self.stationList.count; i++) {
            BRStationListModel *model = self.stationList[i];
            model.isTap = (i == index);
            if (i == index) {
                self.stationView.dto = model;
                self.stationViewBG.hidden = NO;
                WS(weakSelf);
                self.stationView.locationClick = ^{
                    CLLocationCoordinate2D myL = weakSelf.mapView.myLocation;
                    CLLocationCoordinate2D toL = CLLocationCoordinate2DMake(model.lat, model.lng);
                    [BROpenURL openMap:myL toLocation:toL titleAddress:model.address];
                };
                [self.btnStack mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.bottom.equalTo(self.bottomeView.mas_top).offset(-122);
                }];
            }
        }
    } else {
        // 备用方案：如果没有userData，尝试通过坐标匹配（将marker的GCJ02坐标转回BD09再比较）
        CLLocationCoordinate2D markerBd09 = [BRTools br_gcj02ToBd09:marker.position.latitude lng:marker.position.longitude];
        for (BRStationListModel *model in self.stationList) {
            model.isTap = NO;
            // 使用容差比较，因为浮点数精度问题
            if (fabs(model.lat - markerBd09.latitude) < 0.0001 && 
                fabs(model.lng - markerBd09.longitude) < 0.0001) {
                model.isTap = YES;
                self.stationView.dto = model;
                self.stationViewBG.hidden = NO;
                WS(weakSelf);
                self.stationView.locationClick = ^{
                    CLLocationCoordinate2D myL = weakSelf.mapView.myLocation;
                    CLLocationCoordinate2D toL = CLLocationCoordinate2DMake(model.lat, model.lng);
                    [BROpenURL openMap:myL toLocation:toL titleAddress:model.address];
                };
                [self.btnStack mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.bottom.equalTo(self.bottomeView.mas_top).offset(-122);
                }];
                [self.mapView setGMSMarkerShop:self.stationList];
                return YES;
            }
        }
    }
    
    [self.mapView setGMSMarkerShop:self.stationList];
    
    return YES;
}

- (void)br_mapView:(GMSMapView *)mapView didTapInfoWindowOfMarker:(GMSMarker *)marker {
    
}

- (void)br_mapView:(GMSMapView *)mapView didTapAtCoordinate:(CLLocationCoordinate2D)coordinate {
    
    
    [self br_resetMapStation];
}

- (void)br_resetMapStation {
    [self.btnStack mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.bottomeView.mas_top).offset(0);
    }];
    self.stationViewBG.hidden = YES;
    for (BRStationListModel *model in self.stationList) {
        model.isTap = NO;
    }
    
    [self.mapView setGMSMarkerShop:self.stationList];
}

#pragma mark - Lazy Load --
- (BRMapView *)mapView {
    
    if (_mapView == nil) {
        _mapView = [[BRMapView alloc] initWithFrame:CGRectMake(16, kSafeAreaTopHeight, SCREEN_WIDTH - 32, kMap_h)];
//        _mapView.backgroundColor = UIColor.whiteColor;
        _mapView.delegate = self;
    }
    return _mapView;
}


- (BRUnpayView *)unpayView {
    if (_unpayView == nil) {
        _unpayView = [[BRUnpayView alloc] init];
        [_unpayView hidden];
    }
    
    return _unpayView;
}

- (QMUIButton *)listBtn {
    
    if (_listBtn == nil) {
        _listBtn = [[QMUIButton alloc] init];
       [_listBtn setImage:UIImageMake(@"home_nearbyList") forState:UIControlStateNormal];
        _listBtn.layer.cornerRadius = 26;
        _listBtn.layer.masksToBounds = YES;
        [_listBtn addTarget:self action:@selector(toStationList) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _listBtn;
}

- (QMUIButton *)locationBtn {
    if (_locationBtn == nil) {
        _locationBtn = [[QMUIButton alloc] init];
        [_locationBtn setImage:UIImageMake(@"home_location") forState:UIControlStateNormal];
        _locationBtn.layer.cornerRadius = 26;
        _locationBtn.layer.masksToBounds = YES;
        [_locationBtn addTarget:self action:@selector(toMyLocation:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _locationBtn;
}

- (BRHomeBottomView *)bottomeView {
    
    if (_bottomeView == nil) {
        //底部
        _bottomeView = [[BRHomeBottomView alloc] initWithFrame:CGRectMake(0, kScreenHeight - (100 +kSafeAreaBottomHeight), kScreenWidth, 100 +kSafeAreaBottomHeight)];
    }
    return _bottomeView;
}

- (BRHomeTopView *)rentView {
    if (!_rentView) {
        _rentView = [[BRHomeTopView alloc] initWithFrame:CGRectMake(0,kSafeAreaTopHeight + 12, kScreenWidth, 162)];
        [_rentView hidden];
//        _rentView.hidden = YES;
    }
    
    return _rentView;
}

- (BRStatilListTableViewCell *)stationView {
    
    if (_stationView == nil) {
        _stationView = [[[NSBundle mainBundle] loadNibNamed:@"BRStatilListTableViewCell" owner:nil options:nil] lastObject];
        _stationView.backgroundColor = UIColorClear;
        _stationView.contentView.backgroundColor = UIColorClear;
        _stationView.frame = CGRectMake(0, 0, kScreenWidth, 122);
        _stationView.contentBGView.layer.cornerRadius = 24;
    }
    
    return _stationView;
}

- (BOOL)preferredNavigationBarHidden {
    return YES;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
